package com.jungle.common.utils.poi;

import com.alibaba.excel.EasyExcel;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ExcelUtil {

    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");


    public static <T> void exportExcel(List<T> data,String sheetName, Class<T> clazz, HttpServletResponse response){
        try {
            String fileName = fileNameEncode(sheetName);
            respHeaderSetting(response, fileName);
            EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);
        } catch (IOException e) {
            throw new RuntimeException("excel导出异常");
        }
    }

    private static void respHeaderSetting(HttpServletResponse response, String fileName) {
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", "attachment; filename=\""+ fileName +"_"+
                simpleDateFormat.format(new Date())+".xlsx\"");
        response.setHeader("download-filename", fileName);
        response.setContentType("application/octet-stream; charset=UTF-8");
    }

    public static String fileNameEncode(String sheetName){
        return URLEncoder.encode(sheetName, StandardCharsets.UTF_8);
    }
}
